package com.lms.controller;

import com.lms.bean.Type;
import com.lms.service.TypeService;
import com.lms.util.ResultUtils;
import com.lms.vo.TypeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("type")
public class TypeController {
    @Autowired
    private TypeService typeService;

    @RequestMapping("admin/type-list")
    public String toTypeList() {
        return "admin/type-list";
    }


    @RequestMapping("admin/type-input")
    public String toTypeInput(Long typeId, Model model) {
        if(-1==typeId){
            model.addAttribute("operation","添加类别");
            model.addAttribute("type",new Type());
        }else{
            model.addAttribute("operation","更新类别");
            Type type = typeService.findTypeById(typeId);
            model.addAttribute("type",type);
        }
        return "admin/type-input";
    }

    @RequestMapping("save")
    public String save(Long typeId,String typename){
        Type type = new Type();
        type.setTypeId(typeId);
        type.setTypename(typename);
        typeService.save(type);
        return "redirect:admin/type-list";
    }

    @RequestMapping("delete")
    public String delete(Long typeId){
        typeService.deleteById(typeId);
        return "redirect:admin/type-list";
    }

    @RequestMapping("deleteAll")
    public String deleteAll(String ids){
        typeService.deleteAll(ids);
        return "redirect:admin/type-list";
    }

    /**
     * @param pageFromLayUI  计数方式是 1,2,3,4...,n  默认为 1 ;
     *                       但是 Pageable.page 的计数方式是 0,1,2,3,...,n-1 默认为 0
     * @param limitFromLayUI 等于 Pageable.size
     * @return 能被 layUI 接受的 JSON, 格式为 { "code": 0, "msg": "OK", count": 14, "data":[{},{},{}] }
     */
    @RequestMapping("all")
    @ResponseBody
    public ResultUtils<TypeVO> findAll(@RequestParam("page") Integer pageFromLayUI,
                                       @RequestParam("limit") Integer limitFromLayUI,
                                       @RequestParam(value = "queryCondition",defaultValue = "") String queryCondition) {
        //获取记录的总数，交给前端计算分页
        Long count = typeService.getTotalCount(queryCondition);
        //获取当前页的记录列表交给前端渲染,注意 layUI 和 pageable 关于 page 的计数差别
        List<TypeVO> data = typeService.findAll(pageFromLayUI - 1, limitFromLayUI,queryCondition);
        //返回JSON结果
        return ResultUtils.layUITable(count, data);
    }



}
